package com.caochenlei.prototype.deep.mode1;

//身份证对象
class IdCard implements Cloneable {
    private String id;

    public IdCard(String id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return id;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

//代表人对象
public class Person implements Cloneable {
    private String name;
    private int age;
    private IdCard idCard;

    public Person(String name, int age, IdCard idCard) {
        this.name = name;
        this.age = age;
        this.idCard = idCard;
    }

    public IdCard getIdCard() {
        return idCard;
    }

    public void setIdCard(IdCard idCard) {
        this.idCard = idCard;
    }

    @Override
    public String toString() {
        return "Person{" +
                "personHashCode=" + this.hashCode() +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", idCard=" + idCard +
                ", idCardHashCode=" + idCard.hashCode() +
                '}';
    }

    //深克隆我们需要自己手动实现，在引用对象中也需要实现clone方法
    @Override
    protected Object clone() throws CloneNotSupportedException {
        //完成对当前基本数据类型
        //注：String类型通过常量赋值时相当于基本数据类型，通过new关键字创建对象时便是引用数据类型
        Object person = super.clone();

        //对引用类型进行单独处理
        Person p = (Person) person;
        IdCard idCard = (IdCard) p.getIdCard().clone();//实现自己的克隆
        p.setIdCard(idCard);

        return p;
    }
}
